package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.EasyUITree;
import com.jt.pojo.ItemCat;
import com.jt.util.OjbectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/11/3
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;

    @Autowired(required = false)
    private Jedis jedis;


    @Override
    public ItemCat findItemNameById(Long itemCatId) {
        return itemCatMapper.selectById(itemCatId);
    }

    @Override
    @CacheFind("TIMECAT_PARENTID")
    public List<EasyUITree> findItemCatList(Long parentId) {
        QueryWrapper<ItemCat> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        List<ItemCat> list = itemCatMapper.selectList(queryWrapper);
        List<EasyUITree> result = new ArrayList<>();
        for (ItemCat itemCat : list) {
            result.add(new EasyUITree(itemCat.getId(),
                    itemCat.getName(),
                    itemCat.getIsParent() ? "closed" : "open"));
        }
        return result;
    }

    @Override
    public List<EasyUITree> findItemCache(Long id) {
        List<EasyUITree> list = new ArrayList<>();

        String key = "TIMECAT_PARENTID::" + id;

        if (jedis.exists(key)) {
            list = OjbectMapperUtil.toOjbect(jedis.get(key), list.getClass());
        } else {
            list = findItemCatList(id);
            jedis.set(key, OjbectMapperUtil.toJson(list));
        }

        return list;
    }
}
